package com.sf.tools.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;

import com.sf.tools.common.Common;
import com.sf.tools.common.ConnectionFactory;
import com.sf.tools.common.DBUtils;
import com.sf.tools.common.MysqlDao;
import com.sf.tools.common.OracleDao;
import com.sf.tools.common.ProgressHandler;
import com.sf.tools.common.XMLDateSources;
import com.sf.tools.generate.GenerateCode;


public class CodeGenerate{

	private static final long serialVersionUID = 5451299659375745657L;

	private JLabel label1 = new JLabel("数据库类型：");
	private JLabel label2 = new JLabel("ConnectionURL：");
	private JLabel label3 = new JLabel("用户名：");
	private JLabel label4 = new JLabel("密码：");
	private JLabel label5 = new JLabel("模块名称：");
	private JLabel label6 = new JLabel("代码生成路径：");
	private JLabel label7 = new JLabel("数据库表前缀：");
	private JLabel label8 = new JLabel("主键生成序列名：");
	private JLabel label9 = new JLabel("Spring生成方式：");
	private JComboBox combo2 = new JComboBox();
	private JComboBox combo3 = new JComboBox();
	
	private JComboBox combo1 = new JComboBox();
	private JTextField text2 = new JTextField("jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1521:dbName");
	private JTextField text3 = new JTextField("");
	private JPasswordField text4 = new JPasswordField("");
	private JTextField text5 = new JTextField("");
	private JTextField text6 = new JTextField();
	private JButton look = null;
	private JTextField text7 = new JTextField();
	
	private JFileChooser jfc = new JFileChooser();
	
	private JTable tables = null ;
	private JTable table = null ;
	private JTable sourceTables = null;
	
	private JProgressBar task_progress = new JProgressBar();
    private JButton generate = null; // 下一步
    private JButton testBtn = null; // 测试
    private JButton addBtn = null; // 保存
    
    private JPanel con = null;
    private DBUtils dbUtils;
    private Map<String,String> mapping = new HashMap<String,String>();
    private List<String> isQuery = new ArrayList<String>();
    private List<String> isShow = new ArrayList<String>();
    private List<String> isCombo = new ArrayList<String>();
    private JComboBox mapping_table = new JComboBox();
    private JComboBox mapping_column = new JComboBox();
    private JComboBox mapping_column_desc = new JComboBox();
    private String SPLIT_MARK = ":";
    final String[] currSelectTable = new String[1];
    
    private List<String> isGenerate = new ArrayList<String>();
    
    public List<String> isSearch = new ArrayList<String>();
	public List<String> isAdd = new ArrayList<String>();
	public List<String> isUpdate = new ArrayList<String>();
	public List<String> isDelete = new ArrayList<String>();
	public List<String> isImport = new ArrayList<String>();
	public List<String> isExport = new ArrayList<String>();
	
	public CodeGenerate(){
		con = new JPanel();
		
		combo1.setModel(new DefaultComboBoxModel(new String[] {"Oracle"/*, "Mysql"*/}));
		combo2.setModel(new DefaultComboBoxModel(new String[] {}));
		combo3.setModel(new DefaultComboBoxModel(new String[] {"配置文件", "注解"}));
        generate = new JButton("生成"); generate.setEnabled(false);
        testBtn = new JButton("测试");
        addBtn = new JButton("保存");
        look = new JButton("浏览");
        
        JPanel top = new JPanel();
        
        JPanel source = new JPanel();
        source.setLayout(null);
        source.setPreferredSize(new java.awt.Dimension(640, 150));
        source.setBorder(BorderFactory.createTitledBorder("数据源"));
        
        label1.setBounds(30, 20, 100, 20);
        combo1.setBounds(130, 20, 100, 20);
        
        label2.setBounds(30, 50, 100, 20);
        text2.setBounds(130, 50, 300, 20);
        
        label3.setBounds(30, 80, 100, 20);
        text3.setBounds(130, 80, 100, 20);
        
        label4.setBounds(30, 110, 100, 20);
        text4.setBounds(130, 110, 100, 20);
        text4.setEchoChar('*');
        testBtn.setBounds(280, 110, 70, 22);
        addBtn.setBounds(360, 110, 70, 22);
        
        source.add(label1);
        source.add(combo1);

        source.add(label2);
        source.add(text2);
        
        source.add(label3);
        source.add(text3);
        
        source.add(label4);
        source.add(text4);
        source.add(testBtn);
        source.add(addBtn);
        
        JPanel btnPanel = new JPanel();
        btnPanel.setLayout(null);
        btnPanel.setPreferredSize(new java.awt.Dimension(70, 150));
        JButton left = new JButton("<");
        
        JButton del = new JButton("删除");
        left.setBounds(5, 50, 60, 20);
//        right.setBounds(5, 50, 60, 20);
        del.setBounds(5, 80, 60, 20);
        
        btnPanel.add(left);
//        btnPanel.add(right);
        btnPanel.add(del);
        
        int rowHeight=20;
        
        label5.setBounds(20, rowHeight, 100, 20);
        text5.setBounds(120, rowHeight, 150, 20);
        rowHeight+=30;
        
        label8.setBounds(20, rowHeight, 100, 20);
        combo2.setBounds(120, rowHeight, 200, 20);
        rowHeight+=30;
        
        label9.setBounds(20, rowHeight, 100, 20);
        combo3.setBounds(120, rowHeight, 100, 20);
        rowHeight+=30;
        
        label6.setBounds(20, rowHeight, 100, 20);
        text6.setBounds(120, rowHeight, 310, 20);text6.setEditable(false);
        look.setBounds(430, rowHeight, 40, 20);
        rowHeight+=30;
        
        label7.setBounds(20, rowHeight, 100, 20);
        text7.setBounds(120, rowHeight, 310, 20);
        rowHeight+=15;
        
        JLabel label7Desc = new JLabel();
        label7Desc.setForeground(Color.RED);
        label7Desc.setText("<html>说明：用于生成类名时不带前缀.例如:表名为“TB_USER”,则生成类名为“User”,去掉前缀“TB_”;可以输入多个,多个之间用逗号分开.</html>");
        label7Desc.setBounds(120, rowHeight, 320, 50);
        
        String[] titles2 = {"序号","类型","ConnectionURL","用户名","密码"} ;
        Object [][] userInfo2 = {};
        final DefaultTable defaultTable2 = new DefaultTable(1,userInfo2,titles2) ;	// TableModel
        sourceTables = new JTable(defaultTable2) ;
        sourceTables.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        final JScrollPane dataSource = new JScrollPane(sourceTables) ;
        dataSource.setPreferredSize(new java.awt.Dimension(470, 140));
        
        top.add(source,BorderLayout.WEST);
        top.add(btnPanel,BorderLayout.CENTER);
        top.add(dataSource,BorderLayout.EAST);
        
        String[] titles1 = {"是否生成","序号","表名","表描述","查询","新增","修改","删除","导入","导出"} ;
        Object [][] userInfo1 = {};
        final DefaultTable defaultTable1 = new DefaultTable(2,userInfo1,titles1) ;	// TableModel
        tables = new JTable(defaultTable1) ;
        tables.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        final JScrollPane scr1 = new JScrollPane(tables) ;
        scr1.setPreferredSize(new java.awt.Dimension(720, 250));
        
        String[] titles = {"序号","表字段","字段类型","字段描述","关联表","关联字段","显示字段","查询条件","是否显示","下拉列表"} ;
        Object [][] userInfo = {};
        final DefaultTable defaultTable = new DefaultTable(3,userInfo,titles) ;	// TableModel
        table = new JTable(defaultTable) ;
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        final JScrollPane scr = new JScrollPane(table) ;
        scr.setPreferredSize(new java.awt.Dimension(1205, 250));
        
        JPanel progress = new JPanel();
        progress.setLayout(null);
        progress.setPreferredSize(new java.awt.Dimension(1205, 100));
        task_progress.setBounds(0, 70, 1125, 22);
        generate.setBounds(1135, 70, 70, 22);
		progress.add(task_progress);
		progress.add(generate);
		JLabel desc = new JLabel();
		desc.setForeground(Color.RED);
        desc.setText("<html><p>说明：例如字段为dept_id，关联表、关联字段、显示字段为tm_department、dept_id、dept_name,则dept_id关联tm_department表中的dept_id字段,(通常关联的字段都是主键),显示字段为dept_name是指在前台页面展现时,显示的是dept_name字段,如果显示的是dept_code,则显示字段为dept_code.</p><p>查询条件：该字段是否做为查询条件进行查询；是否显示：该字段是否在grid列表中显示；<br>下拉列表：在新增、查询表单中是否做为combo显示，例如：是否有效(1=有效,0=无效)，注意：格式必须为‘xxx(x=xx,x=xx)’,否则将不能正确解析.</p></html>");
        desc.setBounds(0, -10, 1205, 75);
        progress.add(desc);
        
        JPanel test = new JPanel();
        test.add(scr1);
//        JPanel empey = new JPanel();
//        empey.setPreferredSize(new java.awt.Dimension(480, 250));
        JPanel config = new JPanel();
        config.setLayout(null);
        config.setPreferredSize(new java.awt.Dimension(480, 260));
        config.setBorder(BorderFactory.createTitledBorder("基础配置"));
        config.add(label5);
        config.add(text5);
        
        config.add(label8);
        config.add(combo2);
        
        config.add(label9);
        config.add(combo3);
        
        config.add(label6);
        config.add(text6);
        config.add(look);
        
        config.add(label7);
        config.add(text7);
        
        config.add(label7Desc);
        
        test.add(config);
        
        JPanel test2 = new JPanel();
        test2.add(scr);
        
        JPanel tab = new JPanel();
        tab.setLayout(new BorderLayout(5, 5));
        tab.add(test,BorderLayout.NORTH);
        tab.add(test2,BorderLayout.CENTER);
        
//        tables.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        sourceTables.getColumnModel().getColumn(0).setMinWidth(0);
        sourceTables.getColumnModel().getColumn(0).setMaxWidth(0);
        sourceTables.getColumnModel().getColumn(0).setWidth(0);
//        sourceTables.getColumnModel().getColumn(0).setPreferredWidth(40);
        sourceTables.getColumnModel().getColumn(1).setMinWidth(0);
        sourceTables.getColumnModel().getColumn(1).setMaxWidth(0);
        sourceTables.getColumnModel().getColumn(1).setWidth(0);
        sourceTables.getColumnModel().getColumn(2).setPreferredWidth(280);
        sourceTables.getColumnModel().getColumn(3).setPreferredWidth(120);
        sourceTables.getColumnModel().getColumn(4).setMinWidth(0);
        sourceTables.getColumnModel().getColumn(4).setMaxWidth(0);
        sourceTables.getColumnModel().getColumn(4).setWidth(0);
        
        tables.getColumnModel().getColumn(0).setPreferredWidth(80);
        tables.getColumnModel().getColumn(1).setPreferredWidth(40);
        tables.getColumnModel().getColumn(2).setPreferredWidth(190);
        tables.getColumnModel().getColumn(3).setPreferredWidth(195);
        tables.getColumnModel().getColumn(4).setPreferredWidth(35);
        tables.getColumnModel().getColumn(5).setPreferredWidth(35);
        tables.getColumnModel().getColumn(6).setPreferredWidth(35);
        tables.getColumnModel().getColumn(7).setPreferredWidth(35);
        tables.getColumnModel().getColumn(8).setPreferredWidth(35);
        tables.getColumnModel().getColumn(9).setPreferredWidth(35);
        
        table.getColumnModel().getColumn(0).setPreferredWidth(40);
        table.getColumnModel().getColumn(1).setPreferredWidth(130);
        table.getColumnModel().getColumn(2).setPreferredWidth(90);
        table.getColumnModel().getColumn(3).setPreferredWidth(220);
        table.getColumnModel().getColumn(4).setPreferredWidth(130);
        table.getColumnModel().getColumn(5).setPreferredWidth(130);
        table.getColumnModel().getColumn(6).setPreferredWidth(130);
        table.getColumnModel().getColumn(7).setPreferredWidth(80);
        table.getColumnModel().getColumn(8).setPreferredWidth(80);
        table.getColumnModel().getColumn(9).setPreferredWidth(85);
        
        table.getColumnModel().getColumn(4).setCellEditor(new DefaultCellEditor(mapping_table)) ;
        table.getColumnModel().getColumn(5).setCellEditor(new DefaultCellEditor(mapping_column)) ;
        table.getColumnModel().getColumn(6).setCellEditor(new DefaultCellEditor(mapping_column_desc)) ;
        
        con.add(top, BorderLayout.NORTH);
        con.add(tab, BorderLayout.CENTER);
        con.add(progress, BorderLayout.SOUTH);
        
        left.addActionListener(new ActionListener(){
        	@Override
        	public void actionPerformed(ActionEvent e) {
        		int row = sourceTables.getSelectedRow();
        		if(row == -1){
        			return ;
        		}
        		
        		String num = (String) sourceTables.getValueAt(row, 0);
    			String type = (String) sourceTables.getValueAt(row, 1);
    			String url = (String) sourceTables.getValueAt(row, 2);
    			String user = (String) sourceTables.getValueAt(row, 3);
    			String pass = (String) sourceTables.getValueAt(row, 4);
    			
    			System.out.println(num + "-" + type + "-" + url + "-" + user + "-" + pass);
    			combo1.setSelectedItem(type);
    			text2.setText(url);
    			text3.setText(user);
    			text4.setText(pass);
        	}
        });
        addBtn.addActionListener(new ActionListener(){
        	@Override
        	public void actionPerformed(ActionEvent e) {
        		String dbType = (String) combo1.getSelectedItem();
            	String url = text2.getText();
            	String user = text3.getText();
            	String pass = new String(text4.getPassword());
            	
            	try {
					boolean bool = XMLDateSources.add(dbType, url, user, pass);
					if(!bool){
						JOptionPane.showMessageDialog(new JFrame("提示"), "该数据源已存在!");
	        			return ;
					}else{
						loadDataSource(defaultTable2);
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
        	}
        });
        del.addActionListener(new ActionListener(){
        	@Override
        	public void actionPerformed(ActionEvent e) {
        		int row = sourceTables.getSelectedRow();
        		if(row == -1){
        			JOptionPane.showMessageDialog(new JFrame("提示"), "请选择要删除的记录!");
        			return ;
        		}
    			String num = (String) sourceTables.getValueAt(row, 0);
    			
    			System.out.println(num);
    			try {
    				XMLDateSources.delete(num);
					loadDataSource(defaultTable2);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
        	}
        });
//        sourceTables.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
//        	@Override
//        	public void valueChanged(ListSelectionEvent e) {
//        		int row = sourceTables.getSelectedRow();
//        		if(e.getValueIsAdjusting()){
//        			String num = (String) sourceTables.getValueAt(row, 0);
//        			String type = (String) sourceTables.getValueAt(row, 1);
//        			String url = (String) sourceTables.getValueAt(row, 2);
//        			String user = (String) sourceTables.getValueAt(row, 3);
//        			String pass = (String) sourceTables.getValueAt(row, 4);
//        			
//        			System.out.println(num + "-" + type + "-" + url + "-" + user + "-" + pass);
//        		}
//        	}
//        });
        
        look.addActionListener(new ActionListener(){
        	@Override
        	public void actionPerformed(ActionEvent e) {
        		jfc.setDialogTitle("选择文件夹") ;
    			jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    			int state = jfc.showOpenDialog(con);
    			if(state == JFileChooser.APPROVE_OPTION){	// 选择的是确定按钮
    				File f = jfc.getSelectedFile();
    				text6.setText(f.getAbsolutePath());
    			}
        	}
        });
        
        mapping_table.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JComboBox  cb  =  (JComboBox)e.getSource();  
                String  tableName  =  (String)cb.getSelectedItem();
                if(tableName != null){
//                	System.out.println(mapping_column.getItemCount());
                	mapping_column.removeAllItems();
                	mapping_column.addItem(null);
                	mapping_column_desc.removeAllItems();
                	mapping_column_desc.addItem(null);

                	List<String[]> list = dbUtils.findTableByName(tableName);
                	for (String[] columnInfo : list) {
                		mapping_column.addItem(columnInfo[0]);
                		mapping_column_desc.addItem(columnInfo[0]);
                	}
                	
                	//清空已选择的关联列
//                	System.out.println("===="+table.getSelectedRow());
//                	table.setValueAt(null, table.getSelectedRow(), 5);
                }
			}
		});
        final ColorTableRender colorRender = new ColorTableRender();
        tables.getColumn("序号").setCellRenderer(colorRender);
//        mapping_column.addActionListener(new ActionListener() {
//			@Override
//			public void actionPerformed(ActionEvent e) {
//				JComboBox  cb  =  (JComboBox)e.getSource(); 
//				String  columnName  =  (String)cb.getSelectedItem();
//				String table1 = (String) tables.getValueAt(tables.getSelectedRow(), 1);
//				String column1= (String) table.getValueAt(table.getSelectedRow(), 1);
//				String table2= (String) table.getValueAt(table.getSelectedRow(), 4);
//System.out.println(table1 +"--"+ column1 +"    " + table2+"--"+columnName);
////					if(!mapping.containsKey(table1+"="+column1)){
////						if(table2!=null && columnName != null){
////							System.out.println("=========================================");
////							mapping.put(table1+"="+column1, table2+"="+columnName);
////						}
////						if(table2 == null || columnName == null){
////							mapping.remove(table1+"="+column1);
////						}
////					}
//			}
//		});
        
        combo1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JComboBox  cb  =  (JComboBox)e.getSource();  
                String  dbType  =  (String)cb.getSelectedItem();  
                if("Oracle".equals(dbType)){
                	text2.setText("jdbc:oracle:thin:@10.0.13.50:1521:asura");
                	text3.setText("hfls_user");
                	text4.setText("hfls_user");
            	}else if("Mysql".equals(dbType)){
            		text2.setText("jdbc:mysql://10.0.4.52:3306/gamecard");
            		text3.setText("root");
                	text4.setText("123456");
            	}else {
            		text2.setText("");
            		text3.setText("");
                	text4.setText("");
            	}
			}
		});
        
        tables.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        	@Override
        	public void valueChanged(ListSelectionEvent e) {
        		int row = tables.getSelectedRow();
        		if(e.getValueIsAdjusting()){
        			updateCombox();
        			
        			String tableName = (String) tables.getValueAt(row, 2);
        			currSelectTable[0] = tableName;
//        			System.out.println(row + ": " + e.getFirstIndex() + "=" + e.getLastIndex() + "=" + e.getValueIsAdjusting());
            		List<String[]> list = dbUtils.findTableByName(tableName);
            		int count = defaultTable.getRowCount()-1;
            		while(count>=0){
            			defaultTable.removeRow(count);
            			defaultTable.setRowCount(count);
            			count--;
            		}
            		for(int i=0;i<list.size();i++){
            			String key = tableName+SPLIT_MARK+list.get(i)[0];
            			String mapp = mapping.get(key);
            			String[] array = new String[3];
            			if(mapp != null && mapp.length() > 0){
            				array = mapp.split(SPLIT_MARK);
            			}
            			
            			boolean query = isQuery.contains(key)?true:false;
            			boolean show = isShow.contains(key)?true:false;
            			boolean combo = isCombo.contains(key)?true:false;
            			
            			String[] columnInfo = list.get(i);
            			defaultTable.addRow(new Object[]{i+1,columnInfo[0],columnInfo[1],columnInfo[2],array[0],array[1],array[2],query,show,combo});
            			
            		}
        		}
        	}
        });
        
        tables.getTableHeader().setDefaultRenderer(new TablesCheckHeaderCellRenderer(tables));
        table.getTableHeader().setDefaultRenderer(new CheckHeaderCellRenderer(table));
//        table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
//        	@Override
//        	public void valueChanged(ListSelectionEvent e) {
////        		int row = table.getSelectedRow();
//        		if(e.getValueIsAdjusting()){
////System.out.println(row + ": " + table.getValueAt(row, 6)+ ": " + table.getValueAt(row, 7)+ ": " + table.getValueAt(row, 8));
////        			System.out.println(row + ": " + e.getFirstIndex() + "=" + e.getLastIndex() + "=" + e.getValueIsAdjusting());
//        		}
//        	}
//        });
//        table.addMouseListener(new java.awt.event.MouseAdapter(){
//        	@Override
//        	public void mouseClicked(MouseEvent e) {
////        		super.mouseClicked(e);
//        		int row = table.getSelectedRow();
////        		System.out.println(row);
//        		for(int i=0;i<7;i++){
//        			System.out.print(table.getValueAt(row, i) + " ");
//        		}
//        		System.out.println();
//        	}
//        });
        
//		panel.add(button_1);
//		panel.add(button_2);
        testBtn.addActionListener(new ActionListener(){ // 上一步的按钮动作
            public void actionPerformed(ActionEvent e) {
            	testBtn.setEnabled(false);
            	
            	String dbType = (String) combo1.getSelectedItem();
            	String url = text2.getText();
            	String user = text3.getText();
            	String pass = new String(text4.getPassword());
            	
            	String driver = null;
            	if("Oracle".equals(dbType)){
            		driver = "oracle.jdbc.driver.OracleDriver";
            		dbUtils = new OracleDao(driver, url, user, pass);
            	}else if("Mysql".equals(dbType)){
            		driver = "com.mysql.jdbc.Driver";
            		dbUtils = new MysqlDao(driver, url, user, pass);
            	}
            	boolean bool = ConnectionFactory.getIntance().testConnect(driver, url, user, pass);
            	testBtn.setEnabled(true);
            	if(bool){
            		generate.setEnabled(true);
            		JOptionPane.showMessageDialog(new JFrame("提示"), "连接成功!");
            		List<String[]> tableNames = dbUtils.findAllTables();
            		initMappingTable(tableNames);
            		int rowCount = defaultTable1.getRowCount()-1;
            		while(rowCount>=0){
            			defaultTable1.removeRow(rowCount);
            			defaultTable1.setRowCount(rowCount);
            			rowCount--;
            		}
            		for (int i=0;i<tableNames.size();i++){
            			defaultTable1.addRow(new Object[]{false,i+1,tableNames.get(i)[0],tableNames.get(i)[1],false,false,false,false,false,false});
            		}
            		
            		rowCount = defaultTable.getRowCount()-1;
            		while(rowCount>=0){
            			defaultTable.removeRow(rowCount);
            			defaultTable.setRowCount(rowCount);
            			rowCount--;
            		}

            		//主键生成序列combo数据加载
            		List<String> list = dbUtils.getSequences();
            		combo2.removeAllItems();
            		for (String sequ : list) {
            			combo2.addItem(sequ);
					}
            		
            	}else{
            		JOptionPane.showMessageDialog(new JFrame("提示"), "连接失败!");
            		return ;
            	}
            }
        });
        
        /**下面是翻转到卡片布局的某个组件，可参考API中的文档*/
//        button_1.addActionListener(new ActionListener(){ // 上一步的按钮动作
//            public void actionPerformed(ActionEvent e) {
//            	updateCombox();
////                card.previous(pane);
//				System.out.println(mapping);
////				int rowCount = table.getRowCount();
////				for(int i=0;i<rowCount;i++){
////					System.out.println((1+i)+": "+table.getValueAt(i, 6)+" "+table.getValueAt(i, 7)+" "+table.getValueAt(i, 8));
////				}
//				System.out.println(isQuery);
//				System.out.println(isShow);
//				System.out.println(isCombo);
//            }
//        });
        generate.addActionListener(new ActionListener(){ // 下一步的按钮动作
            public void actionPerformed(ActionEvent e) {
            	updateCombox();
System.out.println("isGenerate:"+isGenerate);
System.out.println("isSearch"+isSearch);
System.out.println("isAdd:"+isAdd);
System.out.println("isUpdate:"+isUpdate);
System.out.println("isDelete:"+isDelete);
System.out.println("isImport:"+isImport);
System.out.println("isExport:"+isExport);
//                card.next(pane);
//            	main.setTitle("第2页");
//            	card.show(pane, "p2");
            	
            	task_progress.setValue(0);
            	generate.setEnabled(false);
    			
            	start();
//            	String result = Generate.start();
//    			JOptionPane.showMessageDialog(new JFrame("提示"), result);
            }
        });
        
        loadDataSource(defaultTable2);
	}
	
	private void loadDataSource(DefaultTable defaultTable2){
		List<String[]> sources = new ArrayList<String[]>(0);
		try {
			sources = XMLDateSources.getDataSource();
			int rowCount = defaultTable2.getRowCount()-1;
    		while(rowCount>=0){
    			defaultTable2.removeRow(rowCount);
    			defaultTable2.setRowCount(rowCount);
    			rowCount--;
    		}
			for (int i=0;i<sources.size();i++){
				String[] info = sources.get(i);
				defaultTable2.addRow(new String[]{info[0],info[1],info[2],info[3],info[4]});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void start() {
		final GenerateCode gc = new GenerateCode();
		gc.setProgressHandler(new ProgressHandler(){
			@Override
			public void loadTaskCount(int count) {
				task_progress.setMaximum(count);
				task_progress.setValue(0);
			}
			@Override
			public void doneTaskCount() {
				task_progress.setValue(task_progress.getValue()+1);
			}
		});
		new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					String projectName = text5.getText();
					String generatePath = text6.getText();
					String prefix = text7.getText().replace("，", ",");
					String sequName = (String) combo2.getSelectedItem();
					String generateType = (String) combo3.getSelectedItem();
					String[] prefixs = prefix.split(",");
					
					if(projectName == null || "".equals(projectName.trim())){
						JOptionPane.showMessageDialog(new JFrame("提示"), "模块名称不能为空!");
						return ;
					}
					if(generatePath == null || "".equals(generatePath.trim())){
						JOptionPane.showMessageDialog(new JFrame("提示"), "代码生成路径不能为空!");
						return ;
					}
					if(dbUtils == null){
						JOptionPane.showMessageDialog(new JFrame("提示"), "请先连接数据库!");
						return ;
					}
					
					if(isGenerate.isEmpty()){
						JOptionPane.showMessageDialog(new JFrame("提示"), "请先选择要生成的表!");
						return ;
					}
					Common.SEQUENCE_NAME = sequName;
					Common.GENERATE_SPRING_TYPE = generateType;
					boolean result = gc.generate(isGenerate,dbUtils,isSearch,isAdd,isUpdate,isDelete,isImport,isExport,mapping,isQuery,isShow,isCombo,projectName,generatePath,prefixs);
					
					Thread.sleep(500);
					generate.setEnabled(true);
//					task_progress.setValue(0);
						
//					JOptionPane.showMessageDialog(new JFrame("提示"), "数据字典已成功生成!");
					if(!result){
						JOptionPane.showMessageDialog(new JFrame("提示"), "系统异常，生成失败！");
						return ;
					}
					int statu = JOptionPane.showConfirmDialog(null, 
							"代码已成功生成，是否打开?", "提示", JOptionPane.YES_NO_OPTION);
					if(statu == JOptionPane.OK_OPTION){
						try {
//							Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL Explorer.exe /select," + generatePath);
							java.awt.Desktop.getDesktop().open(new File(generatePath+File.separator+projectName));
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					generate.setEnabled(true);
				}
			}
		}).start();
	}

	protected void updateCombox() {
		String tableName = currSelectTable[0];
//		String  columnName  =  (String)cb.getSelectedItem();
//		String table1 = (String) tables.getValueAt(tables.getSelectedRow(), 1);
//		String column1= (String) table.getValueAt(table.getSelectedRow(), 1);
//		String table2= (String) table.getValueAt(table.getSelectedRow(), 4);
//		String tableName = (String) tables.getValueAt(tables.getSelectedRow(), 1);
		int rowCount = table.getRowCount();
		for(int i=0;i<rowCount;i++){
			String column = (String) table.getValueAt(i, 1);
			
			String mappTable = (String) table.getValueAt(i, 4);
			String mappColumn = (String) table.getValueAt(i, 5);
			String mappColumnDesc = (String) table.getValueAt(i, 6);
			if(mappTable != null && mappColumn != null){
				mapping.put(tableName+SPLIT_MARK+column, mappTable+SPLIT_MARK+mappColumn+SPLIT_MARK+mappColumnDesc);
			}else{
				mapping.remove(tableName+SPLIT_MARK+column);
			}
			
			boolean query = (Boolean) table.getValueAt(i, 7);
			boolean show = (Boolean) table.getValueAt(i, 8);
			boolean combo = (Boolean) table.getValueAt(i, 9);
			String str = tableName+SPLIT_MARK+column;
			if(query){
				if(isQuery.indexOf(str) == -1){
					isQuery.add(str);
				}
			}else{
				isQuery.remove(str);
			}
			if(show){
				if(isShow.indexOf(str) == -1){
					isShow.add(str);
				}
			}else{
				isShow.remove(str);
			}
			if(combo){
				if(isCombo.indexOf(str) == -1){
					isCombo.add(str);
				}
			}else{
				isCombo.remove(str);
			}
		}
		
		rowCount = tables.getRowCount();
		for(int i=0;i<rowCount;i++){
			tableName = (String) tables.getValueAt(i, 2);
			boolean generate = (Boolean) tables.getValueAt(i, 0);
			if(generate){
				if(isGenerate.indexOf(tableName) == -1){
					isGenerate.add(tableName);
				}
			}else{
				isGenerate.remove(tableName);
			}
			
			boolean search = (Boolean) tables.getValueAt(i, 4);
			if(search){
				if(isSearch.indexOf(tableName) == -1){
					isSearch.add(tableName);
				}
			}else{
				isSearch.remove(tableName);
			}
			
			boolean add = (Boolean) tables.getValueAt(i, 5);
			if(add){
				if(isAdd.indexOf(tableName) == -1){
					isAdd.add(tableName);
				}
			}else{
				isAdd.remove(tableName);
			}
			
			boolean update = (Boolean) tables.getValueAt(i, 6);
			if(update){
				if(isUpdate.indexOf(tableName) == -1){
					isUpdate.add(tableName);
				}
			}else{
				isUpdate.remove(tableName);
			}
			
			boolean delete = (Boolean) tables.getValueAt(i, 7);
			if(delete){
				if(isDelete.indexOf(tableName) == -1){
					isDelete.add(tableName);
				}
			}else{
				isDelete.remove(tableName);
			}
			
			boolean imp = (Boolean) tables.getValueAt(i, 8);
			if(imp){
				if(isImport.indexOf(tableName) == -1){
					isImport.add(tableName);
				}
			}else{
				isImport.remove(tableName);
			}
			
			boolean exp = (Boolean) tables.getValueAt(i, 9);
			if(exp){
				if(isExport.indexOf(tableName) == -1){
					isExport.add(tableName);
				}
			}else{
				isExport.remove(tableName);
			}
		}
	}

	protected void initMappingTable(List<String[]> tableNames) {
		mapping_table.removeAllItems();
		mapping_table.addItem(null);
		for (String[] tableName : tableNames) {
			mapping_table.addItem(tableName[0]);
		}
		
		mapping.clear();
		isQuery.clear();
		isShow.clear();
		isCombo.clear();
		
		isGenerate.clear();
		
		isSearch.clear();
		isAdd.clear();
		isUpdate.clear();
		isDelete.clear();
		isImport.clear();
		isExport.clear();
	}

	public Container getCon(){
		return con;
	}
}

class DefaultTable extends DefaultTableModel{
	private static final long serialVersionUID = -4221851586444289033L;
	
//	private String[] titles = {"序号","列名","类型","描述"} ;
//	private Object [][] userInfo = {
//			{"李兴华",30,"男",89,97,186,true} ,
//			{"张三",19,"男",50,50,100,false} ,
//			{"李康",23,"女",90,93,183,false} 
//		} ;	// 定义数据
	private int type;
	public DefaultTable(int type, Object [][] userInfo,String[] titles){
		super(userInfo,titles);
		this.type = type;
	}
	
	public Class<?> getColumnClass(int columnIndex) {	// 得到指定列的类型
		if(this.getValueAt(0,columnIndex) != null){
			return this.getValueAt(0,columnIndex).getClass() ;
		}
		return this.getClass();
	}
	public boolean isCellEditable(int rowIndex, int columnIndex){	// 所有内容都可以编辑
		if(type == 2){
			if(columnIndex == 0 || columnIndex > 2){
				return true;
			}
		}else if(type == 3){
			if(columnIndex > 3){
				return true;
			}
		}
		return false ;
	}
	
	public void selectAllOrNull(boolean value, int selectColumn) {
        for (int i = 0; i < getRowCount(); i++) {
            this.setValueAt(value, i, selectColumn);
        }
    }
}
class ColorTableRender extends DefaultTableCellRenderer {
	
	private static final long serialVersionUID = 7970717277468981320L;

	public Component getTableCellRendererComponent(JTable table,
			Object value, boolean isSelected, boolean hasFocus, int row,
			int column) {
		Component cell = super.getTableCellRendererComponent(table, value,
				isSelected, hasFocus, row, column);
//		if (row <6)  //这里设置行数
//			cell.setBackground(Color.WHITE);
//		else
//			cell.setBackground(new Color(0xee,0xee,0xee));
		return cell;

	}
}
class CheckHeaderCellRenderer implements TableCellRenderer {

	DefaultTable tableModel;
    JTableHeader tableHeader;
    final JCheckBox selectBox;
    final JCheckBox selectBox2;
    final JCheckBox selectBox3;

    public CheckHeaderCellRenderer(JTable table) {
        this.tableModel = (DefaultTable)table.getModel();
        this.tableHeader = table.getTableHeader();
        selectBox = new JCheckBox(tableModel.getColumnName(7));
        selectBox.setSelected(false);
        selectBox2 = new JCheckBox(tableModel.getColumnName(8));
        selectBox2.setSelected(false);
        selectBox3 = new JCheckBox(tableModel.getColumnName(9));
        selectBox3.setSelected(false);
        tableHeader.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() > 0) {
                    //获得选中列
                    int selectColumn = tableHeader.columnAtPoint(e.getPoint());
                    if (selectColumn == 7) {
                        boolean value = !selectBox.isSelected();
                        selectBox.setSelected(value);
                        tableModel.selectAllOrNull(value,selectColumn);
                        tableHeader.repaint();
                    }
                    if (selectColumn == 8) {
                        boolean value = !selectBox2.isSelected();
                        selectBox2.setSelected(value);
                        tableModel.selectAllOrNull(value,selectColumn);
                        tableHeader.repaint();
                    }
                    if (selectColumn == 9) {
                        boolean value = !selectBox3.isSelected();
                        selectBox3.setSelected(value);
                        tableModel.selectAllOrNull(value,selectColumn);
                        tableHeader.repaint();
                    }
                }
            }
        });
    }
    
	@Override
	public Component getTableCellRendererComponent(JTable table, Object value,
			boolean isSelected, boolean hasFocus, int row, int column) {
		String valueStr = (String) value;
        JLabel label = new JLabel(valueStr);
//        label.setHorizontalAlignment(SwingConstants.CENTER); // 表头标签剧中
//        selectBox.setHorizontalAlignment(SwingConstants.CENTER);// 表头标签剧中
        selectBox.setBorderPainted(true);
        selectBox2.setBorderPainted(true);
        selectBox3.setBorderPainted(true);
        JComponent component = label;
        if(column == 7){
        	component = selectBox;
        }else if(column == 8){
        	component = selectBox2;
        }else if(column == 9){
        	component = selectBox3;
        }

        component.setForeground(tableHeader.getForeground());
        component.setBackground(tableHeader.getBackground());
        component.setFont(tableHeader.getFont());
        component.setBorder(UIManager.getBorder("TableHeader.cellBorder"));

        return component;
	}
}

class TablesCheckHeaderCellRenderer implements TableCellRenderer {

	DefaultTable tableModel;
    JTableHeader tableHeader;
    final JCheckBox selectBox;

    public TablesCheckHeaderCellRenderer(JTable table) {
        this.tableModel = (DefaultTable)table.getModel();
        this.tableHeader = table.getTableHeader();
        selectBox = new JCheckBox(tableModel.getColumnName(0));
        selectBox.setSelected(false);
        tableHeader.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() > 0) {
                    //获得选中列
                    int selectColumn = tableHeader.columnAtPoint(e.getPoint());
                    if (selectColumn == 0) {
                        boolean value = !selectBox.isSelected();
                        selectBox.setSelected(value);
                        tableModel.selectAllOrNull(value,selectColumn);
                        tableHeader.repaint();
                    }
                }
            }
        });
    }
    
	@Override
	public Component getTableCellRendererComponent(JTable table, Object value,
			boolean isSelected, boolean hasFocus, int row, int column) {
		String valueStr = (String) value;
        JLabel label = new JLabel(valueStr);
//        label.setHorizontalAlignment(SwingConstants.CENTER); // 表头标签剧中
//        selectBox.setHorizontalAlignment(SwingConstants.CENTER);// 表头标签剧中
        selectBox.setBorderPainted(true);
        JComponent component = label;
        if(column == 0){
        	component = selectBox;
        }

        component.setForeground(tableHeader.getForeground());
        component.setBackground(tableHeader.getBackground());
        component.setFont(tableHeader.getFont());
        component.setBorder(UIManager.getBorder("TableHeader.cellBorder"));

        return component;
	}
}
